package cn.bdqn.witcity.util;

import cn.bdqn.witcity.entity.Order;
import cn.bdqn.witcity.entity.Product;
import cn.bdqn.witcity.entity.User;
import cn.bdqn.witcity.resposity.ProductDao;
import cn.bdqn.witcity.service.OrderService;
import cn.bdqn.witcity.service.ProductService;
import cn.bdqn.witcity.service.UserService;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Component
public class BangKe {
    @Resource
    OrderService orderService;
    @Resource
    ProductService productService;
    @Resource
    UserService userService;
    @Resource
    ProductDao productDao;
    @Resource
    RedisTemplate redisTemplate;

    @RabbitListener(queues = "queue")
    public void pro(Map<String, Object> map) {
        Order order = (Order) map.get("order");
        Integer pid = (Integer) map.get("pid");
        List<User> users = userService.findBangke();
        int count = new Random().nextInt(users.size());
        User user = userService.findById(order.getUid());
        User bangKe = users.get(count);
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init("app.cloopen.com", "8883");
        sdk.setAccount("8aaf0708732220a601733d28ec170bc1", "089c2848f9cd4731a37030acaecdd924");
        sdk.setAppId("8aaf0708732220a601733d28ed000bc8");
        HashMap<String, Object> resultMap = sdk.sendTemplateSMS("19873041207", "1", new String[]{"帮客" +
                bangKe.getUsername() + "收到了您的订单,您要的商品名称是" + order.getProductName() +
                ",数量是" + order.getProductNum() + ",商品总价是" + order.getPrice() + "元,帮客正在派送"});
        if ("000000".equals(resultMap.get("statusCode"))) {
            bangKe.setMoney(bangKe.getMoney() + order.getPrice() * 0.1);
            order.setBid(bangKe.getId());
            orderService.updateOrder(order);
            user.setMoney(user.getMoney() - order.getPrice());
            userService.updateMoney(bangKe);
            userService.updateMoney(user);
            Product product = productService.findProductById(pid);
            product.setStock(product.getStock() - order.getProductNum());
            productService.updateStock(product);
            productDao.save(product);
            String stock = (String) redisTemplate.opsForValue().get(pid.toString());
            Integer newStock = Integer.parseInt(stock) - order.getProductNum();
            redisTemplate.opsForValue().set(pid.toString(), newStock.toString());
        }
    }
}
